package com.prb.client.netty;

import com.prb.client.factory.ProxyFactory;
import com.prb.client.netty.handler.ClientHandler;
import com.prb.client.netty.handler.ClientOutHandler;
import com.prb.netty.AsyncResult;
import com.prb.netty.code.SmartCarDecoder;
import com.prb.netty.code.SmartCarEncoder;
import com.prb.service.IUserService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.HashMap;
import java.util.Map;

public class Client {


    public static Map<String, AsyncResult> asyncMap = new HashMap();

    public static Channel clientChannel;

    /**
     * 连接服务器
     *
     * @param port
     * @param host
     * @throws Exception
     */
    public void connect(int port, String host) throws Exception {
        // 配置客户端NIO线程组  
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            // 客户端辅助启动类 对客户端配置  
            Bootstrap b = new Bootstrap();
            b.group(group)//  
                    .channel(NioSocketChannel.class)//  
                    .option(ChannelOption.TCP_NODELAY, true)//  
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 添加自定义协议的编解码工具
                            ch.pipeline().addLast(new SmartCarEncoder());
                            ch.pipeline().addLast(new SmartCarDecoder());
                            // 处理网络IO
                            ch.pipeline().addLast(new ClientHandler());
                            ch.pipeline().addLast(new ClientOutHandler());
                        }

                    });

            // 异步链接服务器 同步等待链接成功
            ChannelFuture f = b.connect(host, port);

            //进行rpc调用
            doRpc(f);


            f.sync();

            // 等待链接关闭  
            //f.channel().closeFuture().sync();

        } finally {
            group.shutdownGracefully();
            System.out.println("客户端优雅的释放了线程资源...");
        }

    }


    /**
     * 进行rpc 远程调用
     * @param f
     */
    private void doRpc(ChannelFuture f) {
        clientChannel = f.channel();

        //生成代理对象，通过代理请求远程接口
        IUserService userService = (IUserService) ProxyFactory.newProxy(IUserService.class);

        String result = userService.getUserMsg("test");

        System.out.println("result is :" + result);

        System.out.println("client is :" + clientChannel);
    }


    public static void main(String[] args) throws Exception {
        new Client().connect(8088, "127.0.0.1");


    }

}  